﻿/***********************************************************************
 * <copyright file="RepositoryBase.cs" company="BUCA JSC">
 * -->    Copyright (C) statement. All right reserved
 * </copyright>
 * 
 * Created:   LinhMC
 * Email:    linhmc@buca.vn
 * Website:
 * Create Date: Friday, October 18, 2013
 * Usage: 
 * 
 * RevisionHistory: 
 * Date         Author               Description 
 * 
 * ************************************************************************/
using System;
using System.Web;
using AOnlineService.MessageBase;



namespace BucaUIMvc.Repositories.Core
{
    /// <summary>
    /// Base class for all Repositories. 
    /// Provides common repository functionality, including:
    ///   - Management of Service client.
    ///   - Offers common request-response correlation check.
    /// </summary>
    public abstract class RepositoryBase
    {
        /// <summary>
        /// Gets the client.
        /// </summary>
        /// <value>
        /// The client.
        /// </value>
        protected IBigTimeService Client
        {
            get
            {
                // Check if not initialized yet
                if (HttpContext.Current.Session["BigTimeServiceClient"] == null)
                    HttpContext.Current.Session["BigTimeServiceClient"] = new BigTimeService.ServiceImplementations.BigTimeService();

                // If current client is 'faulted' (due to some error), create a new instance.
                var client = HttpContext.Current.Session["BigTimeServiceClient"] as BigTimeService.ServiceImplementations.BigTimeService;
                //if (client != null && client.State == CommunicationState.Faulted)
                //{
                //    try { client.Abort(); }
                //    catch { /* no action */ }

                //    client = new BigTimeServiceClient();
                //    HttpContext.Current.Session["BigTimeServiceClient"] = client;
                //}
                return client;
            }
        }

        /// <summary>
        /// Correlates requestid with returned response correlationId. 
        /// These must always match. If not, request and responses are not related.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        protected void Correlate(RequestBase request, ResponseBase response)
        {
            if (request.RequestId != response.CorrelationId)
                throw new ApplicationException("RequestId and CorrelationId do not match.");
        }
    }
}